package com.sinosoft.taxbenefit.core.SelCustomerInfo.biz.service.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.sinosoft.platform.base.TaxBaseService;
import com.sinosoft.platform.common.util.StringUtil;
import com.sinosoft.taxbenefit.api.base.EBResultCodeDTO;
import com.sinosoft.taxbenefit.api.base.HXResultCodeDTO;
import com.sinosoft.taxbenefit.api.config.ENUM_BZ_RESPONSE_RESULT;
import com.sinosoft.taxbenefit.api.config.ENUM_SENDSERVICE_CODE;
import com.sinosoft.taxbenefit.api.dto.request.base.ParamHeadDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.ThirdSendResponseDTO;
import com.sinosoft.taxbenefit.api.dto.request.customer.ReqSelCustomerInfoDTO;
import com.sinosoft.taxbenefit.api.dto.response.customer.ClaimInfoDTO;
import com.sinosoft.taxbenefit.api.dto.response.customer.CoverageInfoDTO;
import com.sinosoft.taxbenefit.api.dto.response.customer.CustomerQueryResultDTO;
import com.sinosoft.taxbenefit.api.dto.response.customer.PolicyInfoDTO;
import com.sinosoft.taxbenefit.core.SelCustomerInfo.biz.service.SelCustomerInfoService;
import com.sinosoft.taxbenefit.core.SelCustomerInfo.dto.ClaimInfo;
import com.sinosoft.taxbenefit.core.SelCustomerInfo.dto.CoverageInfo;
import com.sinosoft.taxbenefit.core.SelCustomerInfo.dto.CustomerInfo;
import com.sinosoft.taxbenefit.core.SelCustomerInfo.dto.PolicyInfo;
import com.sinosoft.taxbenefit.core.SelCustomerInfo.dto.ReqCustomerQueryInfoDTO;
import com.sinosoft.taxbenefit.core.SelCustomerInfo.dto.ResCustomerQueryInfoDTO;
import com.sinosoft.taxbenefit.core.common.biz.service.CommonCodeService;
import com.sinosoft.taxbenefit.core.common.config.ENUM_RESULT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_EBAO_SERVICE_PORT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUUM_CODE_MAPPING;
import com.sinosoft.taxbenefit.core.common.dto.EbaoServerPortDTO;
import com.sinosoft.taxbenefit.core.common.dto.SendLogDTO;
import com.sinosoft.taxbenefit.core.common.dto.ThirdSendDTO;
import com.sinosoft.taxbenefit.core.ebaowebservice.CustomerQueryService;
import com.sinosoft.taxbenefit.core.ebaowebservice.CustomerQueryService_Service;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseBody;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseHeader;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseJSON;
import com.sinosoft.taxbenefit.core.faultTask.biz.service.FaultTaskService;
import com.sinosoft.taxbenefit.core.transCode.biz.service.TransCodeService;

/**
 * 客户信息查询（调用中保信）
 * @author zhangyu
 * @date 2016年3月11日 下午3:28:10
 */
@Service
public class SelCustomerInfoServiceImpl extends TaxBaseService implements SelCustomerInfoService {
	@Autowired
	CommonCodeService commonCodeService;
	@Autowired
	TransCodeService transCodeService;
	@Autowired
	private FaultTaskService faultTaskService;

	@Override
	public ThirdSendResponseDTO queryCusInfo(ReqSelCustomerInfoDTO reqSelCustomerInfoDTO, ParamHeadDTO paramHeadDTO) {
		ThirdSendResponseDTO thirdSendResponse = new ThirdSendResponseDTO();
		try {
			logger.info("客户概要查询（核心请求）JSON 体数据内容：" + JSONObject.toJSONString(reqSelCustomerInfoDTO));
			// 转换为中保信的DTO
			ReqCustomerQueryInfoDTO reqCustomerQueryInfoDTO = this.thansFor(reqSelCustomerInfoDTO);
			// 2.调用中保信接口服务,获得返回结果 存储调用中保信日志表
			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.CUSTOMER_INFO_QUERY.code(), paramHeadDTO,reqCustomerQueryInfoDTO);
			logger.info("客户概要查询（请求中保信）JSON 数据内容：" + JSONObject.toJSONString(thirdSendDTO));
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			EbaoServerPortDTO ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.CUSTOMER_INFO_QUERY.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			CustomerQueryService_Service service = new CustomerQueryService_Service(wsdlLocation);
			CustomerQueryService servicePort = service.getCustomerQueryServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.query(thirdSendDTO.getHead(), thirdSendDTO.getBody(),responseHeaderHolder, responseBodyHolder);
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("客户概要查询（中保信响应）JSON 数据内容：" + responseBody.getJsonString());
			// 封装中保信返回报文
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);
			// 封装发送报文日志对象
			SendLogDTO sendLog = new SendLogDTO();
			sendLog.setSerialNo(paramHeadDTO.getSerialNo());
			sendLog.setPortCode(ENUM_EBAO_SERVICE_PORT_CODE.CUSTOMER_INFO_QUERY.code());
			sendLog.setRequestContent(JSONObject.toJSONString(thirdSendDTO));
			sendLog.setResponseContent(JSONObject.toJSONString(responseJSON));
			sendLog.setTargetCode(ENUM_SENDSERVICE_CODE.EBAO.code());
			sendLog.setState(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
			sendLog.setDescription(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			commonCodeService.addLogSend(sendLog);
			// 3.封装返回核心dto;
			if (ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())
					|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())) {
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			}else{
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				List list = responseHeader.getResultMessage().getMessage();
				if(list != null && list.size() > 0){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : responseHeader.getResultMessage().getMessage()){
						sbStr.append(mess).append("|");
					}
					String message = sbStr.substring(0, sbStr.length()-1).toString();
					thirdSendResponse.setResultDesc(message);
				}else{
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				}
			}
			CustomerQueryResultDTO CustomerQueryResultDTO = new CustomerQueryResultDTO();
			if (!StringUtil.isEmpty(responseBody.getJsonString())) {
				// 接收中保信返回的DTO
				ResCustomerQueryInfoDTO resSelCustomerInfoDTO = JSONObject.parseObject(responseBody.getJsonString(),ResCustomerQueryInfoDTO.class);
				// 封装返回给核心的DTO
				CustomerQueryResultDTO = this.ChangeDTO(resSelCustomerInfoDTO);
			}
			thirdSendResponse.setResJson(CustomerQueryResultDTO);
		} catch (Exception e) {
			logger.error("客户概要查询失败" + e.getMessage());
			e.printStackTrace();
			thirdSendResponse.setResJson(e.getMessage());
			thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
			thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
			thirdSendResponse.setResJson(e.getMessage());
		}
		logger.error("客户概要查询后置处理结束!");
		return thirdSendResponse;
	}
	/**
	 * 把核心请求的DTO转成中保信的DTO
	 * 
	 * @param reqSelCustomerInfoDTO
	 * @return
	 */
	public ReqCustomerQueryInfoDTO thansFor(ReqSelCustomerInfoDTO reqSelCustomerInfoDTO) {
		ReqCustomerQueryInfoDTO reqCustomerQueryInfoDTO = new ReqCustomerQueryInfoDTO();
		CustomerInfo customerDTO = new CustomerInfo();
		customerDTO.setApplyNo(reqSelCustomerInfoDTO.getCustomer().getApplyNo());
		customerDTO.setCustomerNo(reqSelCustomerInfoDTO.getCustomer().getCustomerNo());
		customerDTO.setEndDate(reqSelCustomerInfoDTO.getCustomer().getEndDate());
		customerDTO.setPolicyNo(reqSelCustomerInfoDTO.getCustomer().getPolicyNo());
		customerDTO.setStartDate(reqSelCustomerInfoDTO.getCustomer().getStartDate());
		customerDTO.setTaxDiscountedIndi(reqSelCustomerInfoDTO.getCustomer().getTaxDiscountedIndi());
		reqCustomerQueryInfoDTO.setCustomer(customerDTO);
		reqCustomerQueryInfoDTO.setOperator(reqSelCustomerInfoDTO.getOperator());
		return reqCustomerQueryInfoDTO;
	}
	/**
	 * 把中保信返回的DTO转成核心的DTO
	 * @param resSelCustomerInfoDTO
	 * @return
	 */
	public CustomerQueryResultDTO ChangeDTO(ResCustomerQueryInfoDTO resSelCustomerInfoDTO) {
		CustomerQueryResultDTO customerQueryResultDTO = new CustomerQueryResultDTO();
		// 遍历保单列表
		if (null != resSelCustomerInfoDTO.getCustomer()) {
			List<PolicyInfoDTO> policyList = new ArrayList<PolicyInfoDTO>();
			customerQueryResultDTO.setCustomerNo(resSelCustomerInfoDTO.getCustomer().getCustomerNo());
			customerQueryResultDTO.setNationality(resSelCustomerInfoDTO.getCustomer().getNationality());
			if(null != resSelCustomerInfoDTO.getCustomer().getPolicyList()){
				for (PolicyInfo policyInfo : resSelCustomerInfoDTO.getCustomer().getPolicyList()) {
					PolicyInfoDTO policyInfoDTO = new PolicyInfoDTO();
					policyInfoDTO.setCompanyCode(policyInfo.getCompanyCode());
					policyInfoDTO.setEffectiveDate(policyInfo.getEffectiveDate());
					policyInfoDTO.setExpireDate(policyInfo.getExpireDate());
					policyInfoDTO.setPeriodPayment(policyInfo.getPeriodPayment());
					policyInfoDTO.setPolicyNo(policyInfo.getPolicyNo());
					policyInfoDTO.setPolicySource(policyInfo.getPolicySource());
					policyInfoDTO.setPolicyStatus(transCodeService.transCode(ENUUM_CODE_MAPPING.STATE.code(), policyInfo.getPolicyStatus()));
					policyInfoDTO.setPolicytotalPayment(policyInfo.getPolicytotalPayment());
					policyInfoDTO.setPolicyType(policyInfo.getPolicyType());
					policyInfoDTO.setSequenceNo(policyInfo.getSequenceNo());
					policyInfoDTO.setTaxFavorIndi(policyInfo.getTaxFavorIndi());
					policyInfoDTO.setTerminationDate(policyInfo.getTerminationDate());
					policyInfoDTO.setTerminationReason(transCodeService.transCode(ENUUM_CODE_MAPPING.TERMINATIONREASON.code(), policyInfo.getTerminationReason()));
					// 遍历包含在保单列表下的险种列表
					if(null != policyInfo.getCoverageList()){
						List<CoverageInfoDTO> coverageList = new ArrayList<CoverageInfoDTO>();
						for (CoverageInfo coverageInfo : policyInfo.getCoverageList()) {
							CoverageInfoDTO coverageInfoDTO = new CoverageInfoDTO();
							coverageInfoDTO.setComCoverageName(coverageInfo.getComCoverageName());
							coverageInfoDTO.setSa(coverageInfo.getSa());
							coverageInfoDTO.setUnderwritingDecision(coverageInfo.getUnderwritingDecision());
							coverageList.add(coverageInfoDTO);
						}
						policyInfoDTO.setCoverageList(coverageList);
					}
					policyList.add(policyInfoDTO);
				}
				customerQueryResultDTO.setPolicyList(policyList);
			}
			if(null != resSelCustomerInfoDTO.getCustomer().getClaimList()){
				List<ClaimInfoDTO> claimList = new ArrayList<ClaimInfoDTO>();
				// 遍历赔案列表
				for (ClaimInfo claimInfo : resSelCustomerInfoDTO.getCustomer().getClaimList()) {
					ClaimInfoDTO claimInfoDTO = new ClaimInfoDTO();
					claimInfoDTO.setAccidentDate(claimInfo.getAccidentDate());
					claimInfoDTO.setClaimConclusionCode(transCodeService.transCode(ENUUM_CODE_MAPPING.CLAIMCONCLUSIONCODE.code(),claimInfo.getClaimConclusionCode()));
					claimInfoDTO.setEndcaseDate(claimInfo.getEndcaseDate());
					claimInfoDTO.setWarningDesc(claimInfo.getWarningDesc());
					claimInfoDTO.setWarningIndi(claimInfo.getWarningIndi());
					claimList.add(claimInfoDTO);
				}
				customerQueryResultDTO.setClaimList(claimList);
			}
		}
		EBResultCodeDTO eBResultCode = resSelCustomerInfoDTO.getResult();
		HXResultCodeDTO hxResultCode = new HXResultCodeDTO();
		hxResultCode.setResultCode(eBResultCode.getResultCode());
		String message = "";
		if (null != eBResultCode.getResultMessage()) {
			StringBuffer sbStr = new StringBuffer();
			for (String mess : eBResultCode.getResultMessage()) {
				sbStr.append(mess).append("|");
			}
			message = sbStr.substring(0, sbStr.length() - 1).toString();
		}
		hxResultCode.setResultMessage(message);
		customerQueryResultDTO.setResult(hxResultCode);
		return customerQueryResultDTO;
	}
}